﻿using System.Web.Profile;
using System.IO;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Marbles.Core.Web.Controls
{
    [ToolboxData("<{0}:ThemeSelector runat=server></{0}:ThemeSelector>")]
    public class ThemeSelector : WebControl
    {

        [Category("Actions")]
        public event EventHandler ThemeChanged;

        [Category("Appearance")]
        public string SelectedTheme
        {
            get
            {
                object obj = ViewState["SelectedTheme"];
                if (obj == null) { return Page.Theme; }
                return (string)obj;
            }
            set { ViewState["SelectedTheme"] = value; }
        }

        [Category("Behaviour")]
        public bool AutoPostback
        {
            get
            {
                object obj = ViewState["AutoPostback"];
                if (obj == null) { return false; }
                return (bool)obj;
            }
            set { ViewState["AutoPostback"] = value; }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            DropDownList drp = new DropDownList();
            drp.ID = this.ID + "_Selector";
            drp.DataSource = GetThemes();
            drp.DataBind();
            drp.AutoPostBack = this.AutoPostback;
            drp.SelectedIndexChanged += new EventHandler(drpTheme_SelectedIndexChanged);
            drp.Items.Insert(0, new ListItem(string.Empty, string.Empty));
            drp.SelectedValue = this.SelectedTheme;
            this.Controls.Add(drp);
        }

        protected void drpTheme_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList drp = sender as DropDownList;
            DefaultProfile pc = HttpContext.Current.Profile as DefaultProfile;
            this.SelectedTheme = drp.SelectedValue;
            if (ThemeChanged != null) { ThemeChanged(this, EventArgs.Empty); }
        }

        private string[] GetThemes()
        {
            string dirname = HttpContext.Current.Server.MapPath("~/App_Themes");
            string[] themes = Directory.GetDirectories(dirname, "*.*", SearchOption.TopDirectoryOnly);
            List<string> themenames = new List<string>();

            foreach (string theme in themes)
            {
                DirectoryInfo info = new DirectoryInfo(theme);
                themenames.Add(info.Name);
            }

            return themenames.ToArray();
        }
    }

}
